﻿/**

 @Name：swui.dektop 桌面模块
 @Author：Zxq
 @License：MIT
    
 */
layui.define(['jquery', 'swui'], function (exports) {
    "use strict";

    var $ = layui.jquery;

    //桌面构造函数
    var Desktop = function () {
        swui.baseObject.call(this, 'desktop');
        this.desktops = {};
    };

    Desktop.prototype = {
        //初始化html元素及事件
        render: function (callback) {
            var othis = this;
            othis.elem = othis.configs.elem || $('.swui-desktop');
    
            othis.setData({urlcode:'uidesktop'}, function (data) {
                othis.data = data;
                othis.renderElems();
                //调用渲染完毕的回调函数
                if (othis.Utils.isFunction(callback))
                    callback.call(this, othis);
            });
        }
        //渲染HTML
        ,renderElems: function () {
            if (this.data.length === 0) return;
            var othis = this;
            $(othis.data).each(function (index, item) {
                othis.addApp(item);
            });
            //定位应用
            othis.locaApp();
            othis.resetEvents();
        }
        //重置桌面应用事件
        ,resetEvents: function(){
            var othis = this,
                context = this.configs.contextmenu || [],
                dmenu = this.configs.desktopmenu || [],
                events = this.configs.events || [];
            //桌面区域右键菜单定义
            othis.resetEvent('mouseup', othis.elem, function (e) {
                var target = e.target||e.srcElement;
                var $div = $(target).closest('div.swui-desktop-item');
                if (e.button === 2) {
                    if ($div.length === 0) {//空白处右键功能
                        var pos = {left:e.clientX+'px',top:e.clientY+'px'};
                        othis.ContextMenu(null, dmenu, 'app-contextmenu', pos);
                    }
                    else {//桌面应用右键功能
                        var code = $div.data('code');
                        var pos = {left:e.clientX+'px',top:e.clientY+'px'};
                        othis.ContextMenu(null, context, 'app-contextmenu', pos, othis.desktops[code], { reLocaApp: function(){ othis.locaApp(othis.elem); } });

                        //添加移除选中状态
                        $div.addClass(othis.cssName.THIS);
                    }
                }
                else if (e.button === 0) {
                    $div.toggleClass(othis.cssName.THIS);
                }
            });
            //桌面应用其它事件(单击、双击等等)
            for (var evt in events) {
                othis.resetEvent(evt, '> .swui-desktop-item', function (event) {
                    var type = event.type;
                    if (!othis.Utils.isFunction(events[type]))
                        return;
                    var code = $(this).data('code');
                    events[type].call(this, othis.desktops[code]);
                    //移除选中状态
                    othis.elem.find('>.swui-desktop-item.'+othis.cssName.THIS).removeClass(othis.cssName.THIS);
                    othis.sp(event);//阻止事件冒泡
                },othis.elem);
            }
        }
        ,resizeEvent: function(e){
            this.locaApp();
        }
        //添加桌面应用
        ,addApp: function (option, callback) {
            option = option || {};
            if (!option.code) return;
            var destopItem = this.elem.children('div[data-code="'+option.code+'"]');
            if (destopItem.length === 0) {
                this.desktops[option.code] = option;
                var html = '<div class="swui-desktop-item" data-code="'+option.code+'"'+(option.help?' data-help="'+option.help+'"':'')+'>'+function(){
                        if (option.icon.indexOf('<fa>')===0) {//以<fa>开头表示font-awesome图标
                            return '<div class="swui-icon-font"><i class="fa ' + option.icon.substr(4) + ' fa-fw"></i></div>';
                        }
                        else if (option.icon.indexOf('<layui>')===0) {//以<layui>开头表示layui图标
                            return '<div class="swui-icon"><i class="layui-icon ' + option.icon.substr(7) + '"></i></div>';
                        }
                        else {//默认为图片的路径
                            return '<div class="swui-icon"><img src="' + option.icon + '" /></div>';
                        }
                    }()+'<p>' + option.name + '</p>';
                destopItem = $(html).appendTo(this.elem);
            }
            if (this.Utils.isFunction(callback)) {
                callback(destopItem);
            }
            if (this.configs.moveable) {
                var w = this.elem.outerWidth(),h = this.elem.outerHeight();
                var thisElem = this.elem;
                //桌面应用允许移动
                drag.init(destopItem[0],{
                    container:this.elem[0],
                    cursor:false,
                    mirror:true,
                    //Moving:function(el){console.log(el.style.left+','+el.style.top);},
                    mirrorEnd:function(el,pos){
                        pos.left = Math.floor(pos.X/90)*90;
                        pos.top = Math.floor(pos.Y/100)*100;
                        if (pos.left+90>w) pos.left -= 90;
                        if (pos.top+100>h) pos.top -= 100;
                        var items = thisElem.find('div.swui-desktop-item');
                        for (var i=0;i<items.length;i++) {
                            var offset = $(items[i]).offset();
                            if (pos.left === offset.left && pos.top === offset.top) {
                                offset = $(el).offset();
                                $(items[i]).animate(offset, {duration: 500});
                                break;
                            }
                        }
                        $(el).animate(pos, {duration: 500});
                    }
                });
            }
            
            return destopItem;
        }
        //移除桌面应用
        ,removeApp: function (option, callback) {
            option = option || {};
            var destopItem;
            if (this.Utils.isString(option))
                destopItem = this.elem.children('div[data-code="'+option+'"]');
            else if (!option.code) return;
            else destopItem = this.elem.children('div[data-code="'+option.code+'"]');
            if (destopItem.length > 0) {
                destopItem.remove();
            }
            if (this.Utils.isFunction(callback)) {
                callback(destopItem);
            }
        }
        //定位桌面应用  ----待处理----移动图标后，resize页面后，被移动图标的因为标记了位置而不能自动排位
        ,locaApp: function () {
            //计算一竖排能容纳几个应用
            var cnt = parseInt(this.elem.outerHeight() / 100);
            this.elem.attr('class', this.elem.attr('class').replace(/\brows.*?\b/g, '').replace(/(^\s*)|(\s*$)/g, ""));
            this.elem.addClass('rows'+cnt);
            /*var items = this.elem.find('div.swui-desktop-item');
            for(var i=0;i<items.length;i++) {
                var left = 90*(Math.floor(i/cnt));
                var top = 100*(i%cnt);
                $(items[i]).css({left:left,top:top});
            }*/
        }
    }

    var desktop = new Desktop();

    swui.desktop = desktop;

    exports(desktop.MOD_NAME, {});

    delete layui.desktop;
});